const app = getApp();
import QQMapWX from "../../utils/qqmap-wx-jssdk.min"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 防止滚动穿透
    isStopBodyScroll: false,
    // 上传图片预览
    fileList: [],
    // 修改地图位置显隐
    showMap: true,
    // 设施弹框显隐
    facilityPopup: false,
    // 查询设施表单
    facilityForm: {
      facilityName: "",
      pageSize: 20,
      pageNum: 1,
    },
    // 设施数据
    facilityInfo: [],
    // 部件弹框显隐
    partsPopup: false,
    // 部件名称显示
    partsName: "",
    // 查询部件表单
    partsForm: {
      facilityUuid: "",
      partUuid: "",
      partsName: ""
    },
    // 部件数据
    partsInfo: [],
    // 对向车道复选框
    checked: false,
    // 构件弹框显隐
    componentPopup: false,
    // 构件名称显示
    componentName: "",
    // 查询构件信息表单
    componentForm: {
      facilityUuid: "",
      partUuid: "",
      sourceType: "",
      componentUuid: "",
      pageNum: 1,
      pageSize: 20
    },
    // 构件信息
    componentInfo: [],
    // 构件编号
    componentCode: "",
    // 设施方向
    componentDirection: "",
    // 损害弹框显隐
    diseasePopup: false,
    // 损害名称显示
    diseaseName: "",
    // 查询损害表单
    diseaseForm: {
      componentTypeUuid: "",
    },
    // 程度说明显隐
    degreeShow: false,
    // 提交病害上报表单
    submitForm: {
      company: "",
      componentUuid: "",
      damageDegree: 0,
      damageUuid: "",
      facilitiesDirection: "",
      facilitiesName: "",
      facilityUuid: "",
      img1: "",
      img2: "",
      img3: "",
      img4: "",
      img5: "",
      img6: "",
      latitude: "",
      longitude: "",
      limitTime: "",
      oppositeLane: 0,
      partUuid: "",
      place: "",
      problemDescribe: "",
      problemNum: "",
      reportPername: "",
      reportUserId: "",
      sourceUnit: "",
      sourceUnitType: "",
    },
    facilityEmpty: false,
    partsEmpty: false,
    componentEmpty: false,
  },
  // 多文件上传
  afterRead(e) {
    console.log(e);
    console.log(app.globalData.url + 'file/uploadd');
    const { file } = e.detail;
    file.map(item => {
      wx.uploadFile({
        url: app.globalData.url + 'file/uploadd',
        filePath: item.url,
        name: 'file',
        formData: { 'file': file.url },
        success: res => {
          console.log(JSON.parse(res.data));
          if (res.statusCode == 200) {
            const { url } = JSON.parse(res.data)
            // 上传完成需要更新 fileList
            const { fileList = [] } = this.data;
            fileList.push({ ...file, url: url });
            this.setData({ fileList });
          }

        },
        fail: err => {
          console.log(err);
        }
      });
    })
  },
  // 删除图片
  delete(e) {
    let fileList = this.data.fileList
    fileList.splice(e.detail.index, 1)
    this.setData({
      fileList
    })
  },


  // -----start地图定位start-----
  Location() {
    var that = this;
    //获取当前的地理位置、速度
    wx.getLocation({
      // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      type: "gcj02",
      altitude: true,//开启高精度定位
      success: function (res) {
        //赋值经纬度
        that.setData({
          'submitForm.latitude': res.latitude,
          'submitForm.longitude': res.longitude,
        })
        // 腾讯地图逆地址解析
        let qqmapsdk = new QQMapWX({
          key: 'XH6BZ-UBFRS-KCYOQ-6X3QI-H3QKK-E4BD7'
        })
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: (res) => {
            console.log(res);
            if (res.status == 0) {
              that.setData({
                'submitForm.place': `${res.result.address}-${res.result.formatted_addresses.recommend}`
              })
            }
          }
        })
        that.getFacilityInfo();
      }
    })
  },
  // 修改地图坐标
  regionchange(e) {
    // 地图发生变化的时候，获取中间点，也就是用户选择的位置toFixed
    if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
      var that = this;
      this.mapCtx = wx.createMapContext("map4select");
      this.mapCtx.getCenterLocation({
        type: 'gcj02',
        altitude: true,//开启高精度定位
        success: function (res) {
          that.setData({
            'submitForm.latitude': res.latitude,
            'submitForm.longitude': res.longitude,
          })
          // 腾讯地图逆地址解析
          let qqmapsdk = new QQMapWX({
            key: 'XH6BZ-UBFRS-KCYOQ-6X3QI-H3QKK-E4BD7'
          })
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: (res) => {
              console.log(res);
              if (res.status == 0) {
                that.setData({
                  'submitForm.place': `${res.result.address}-${res.result.formatted_addresses.recommend}`
                })
              }
            }
          })
          that.getFacilityInfo();
        }
      })
    }
  },
  // 修改定位地图显隐
  dialogShow() {
    this.setData({
      showMap: false
    })
  },
  // -----end修改地图坐标确认后关闭end-----
  onCloseDialog() {
    this.setData({
      showMap: true
    })
  },

  // -----start设施弹出层关闭start-----
  facilityClose() {
    this.setData({
      'facilityForm.facilityName': "",
      facilityPopup: false,
      isStopBodyScroll: false,
    })
    this.getFacilityInfo();
  },
  // 控制设施弹出层显隐
  selectFacility() {
    this.setData({
      facilityPopup: true,
      isStopBodyScroll: true,
      // 重置部件名称
      partsName: "",
      // 重置对向车道
      checked: false,
      // 重置构件名称
      componentName: "",
      // 重置构件编号
      componentCode: "",
      // 重置设施方向
      componentDirection: "",
      // 重置损害名称
      diseaseName: "",
      // 重置损害程度
      'submitForm.damageDegree': 0,
      // 重置问题数量
      'submitForm.problemNum': "",
      // 重置处理时限（小时）
      'submitForm.limitTime': "",
      // 重置问题描述
      'submitForm.problemDescribe': "",
    })
    // 刷新部件信息
    this.getPartsInfo();
  },
  // 设施搜索
  facilitySearch(e) {
    this.setData({
      'facilityForm.facilityName': e.detail
    })
    // 重新获取设施信息
    this.getFacilityInfo();
  },
  // 获取设施信息
  getFacilityInfo() {
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        if (res.errMsg = "getStorage:ok") {
          app.wxRequest("GET", "selectFacilityByLonLatC", {
            longitude: this.data.submitForm.longitude,
            latitude: this.data.submitForm.latitude,
            userUuid: res.data.userId,
            facilityName: this.data.facilityForm.facilityName,
            pageSize: this.data.facilityForm.pageSize,
            pageNum: this.data.facilityForm.pageNum
          }, (res) => {
            console.log(res);
            if (res.errcode == 0) {
              this.setData({
                facilityInfo: res.data.content
              })
              res.data.content ? this.setData({
                facilityEmpty: false
              }) : this.setData({
                facilityEmpty: true
              })
            }
          }, (err) => {
            console.log(err)
          })
        }

      }
    });
  },
  // 设施下拉加载数据
  facilityLoad(e) {
    this.setData({
      'facilityForm.pageSize': this.data.facilityForm.pageSize + 20
    })
    this.getFacilityInfo();
  },
  // -----end选中当前设施信息 赋值 关闭弹框end-----
  clickFacility(e) {
    const [id, name] = e.currentTarget.dataset.index;
    this.setData({
      'partsForm.facilityUuid': id,
      'componentForm.facilityUuid': id,
      'submitForm.facilitiesName': name,
      'submitForm.facilityUuid': id,
      'facilityForm.facilityName': "",
      facilityPopup: false,
      isStopBodyScroll: false
    })
  },


  // -----start部件弹出层关闭start-----
  partsClose() {
    this.setData({
      'partsForm.partsName': "",
      partsPopup: false,
      isStopBodyScroll: false,
    })
  },
  // 控制部件弹出层显隐
  selectParts() {
    // 获取部件信息
    this.getPartsInfo();
    this.setData({
      partsPopup: true,
      isStopBodyScroll: true,
      // 重置对向车道
      checked: false,
      // 重置构件名称
      componentName: "",
      // 重置构件编号
      componentCode: "",
      // 重置设施方向
      componentDirection: "",
      // 重置损害名称
      diseaseName: "",
      // 重置损害程度
      'submitForm.damageDegree': 0,
      // 重置问题数量
      'submitForm.problemNum': "",
      // 重置处理时限（小时）
      'submitForm.limitTime': "",
      // 重置问题描述
      'submitForm.problemDescribe': "",
    })
  },
  // 部件搜索
  partsSearch(e) {
    this.setData({
      'partsForm.partsName': e.detail
    })
    // 重新获取部件信息
    this.getPartsInfo();
  },
  // 获取部件信息
  getPartsInfo() {
    if (this.data.partsForm.facilityUuid == "") return;
    app.wxRequest("GET", "selectParts", this.data.unitForm, (res) => {
      console.log(res);
      if (res.errcode == 0) {
        this.setData({
          partsInfo: res.data.content
        })
        res.data.content ? this.setData({
          partsEmpty: false
        }) : this.setData({
          partsEmpty: true
        })
      }

    }, (err) => {
      console.log(err)
    })
  },
  // -----end选中当前部件信息 赋值 关闭弹框end-----
  clickParts(e) {
    const [id, name] = e.currentTarget.dataset.index;
    this.setData({
      // 'unitForm.partUuid': id,
      'componentForm.partUuid': id,
      'submitForm.partUuid': id,
      partsName: name,
      'partsForm.partsName': "",
      partsPopup: false,
      isStopBodyScroll: false
    })
  },


  // -----end对向车道选择end-----
  oppositeCheck(e) {
    e.detail ? this.setData({
      'submitForm.oppositeLane': 1
    }) : this.setData({
      'submitForm.oppositeLane': 0
    })
    this.setData({
      checked: e.detail,
    });
  },


  // -----start构件弹出层关闭start-----
  componentClose() {
    this.setData({
      componentPopup: false,
      isStopBodyScroll: false,
    })
  },
  // 控制构件弹出层显隐
  selectComponent() {
    // 获取构件信息
    this.getComponentInfo();
    this.setData({
      isStopBodyScroll: true,
      componentPopup: true,
      // 重置损害名称
      diseaseName: "",
      // 重置损害程度
      'submitForm.damageDegree': 0,
      // 重置问题数量
      'submitForm.problemNum': "",
      // 重置处理时限（小时）
      'submitForm.limitTime': "",
      // 重置问题描述
      'submitForm.problemDescribe': "",
    })
  },
  // 构件搜索
  componentSearch(e) {
    console.log(e);
  },
  // 获取构件信息
  getComponentInfo() {
    if (this.data.componentForm.facilityUuid == "" || this.data.componentForm.partUuid == "") return;
    app.wxRequest("GET", "selectComponent", this.data.componentForm, (res) => {
      console.log(res);
      if (res.errcode == 0) {
        this.setData({
          componentInfo: res.data.content
        })
        res.data.content ? this.setData({
          componentEmpty: false
        }) : this.setData({
          componentEmpty: true
        })
      }
    }, (err) => {
      console.log(err)
    })
  },
  // 构件下拉加载数据
  componentLoad(e) {
    this.setData({
      'componentForm.pageSize': this.data.componentForm.pageSize + 20
    })
    this.getComponentInfo();
  },
  // -----end选中当前构件信息 赋值 关闭弹框end-----
  clickComponent(e) {
    const [typeId, id, name, direction, code,] = e.currentTarget.dataset.index;
    this.setData({
      'submitForm.componentUuid': id,
      componentName: name,
      componentCode: code,
      componentDirection: direction,
      'submitForm.facilitiesDirection': direction,
      componentPopup: false,
      'diseaseForm.componentTypeUuid': typeId,
      isStopBodyScroll: false,
    })
  },

  // -----start损害弹出层关闭start-----
  diseaseClose() {
    this.setData({
      diseasePopup: false,
      isStopBodyScroll: false,
    })
  },
  // 控制损害弹出层显隐
  selectDisease() {
    this.getDiseaseInfo();
    this.setData({
      diseasePopup: true,
      isStopBodyScroll: true,
      // 重置损害程度
      'submitForm.damageDegree': 0,
      // 重置问题数量
      'submitForm.problemNum': "",
      // 重置处理时限（小时）
      'submitForm.limitTime': "",
      // 重置问题描述
      'submitForm.problemDescribe': "",
    })
  },
  // 损害搜索
  diseaseChange(e) {

  },
  // 获取损害信息
  getDiseaseInfo() {
    if (this.data.diseaseForm.componentTypeUuid == "") return;
    app.wxRequest("GET", "selectDisease", this.data.diseaseForm, (res) => {
      console.log(res);
      if (res.errcode == 0) {
        this.setData({
          diseaseInfo: res.data.content
        })
        res.data.content ? this.setData({
          diseaseEmpty: false
        }) : this.setData({
          diseaseEmpty: true
        })
      }
    }, (err) => {
      console.log(err)
    })
  },
  // -----end选中当前损害信息 赋值 关闭弹框end-----
  clickDisease(e) {
    const [id, name, type] = e.currentTarget.dataset.index;
    this.setData({
      'submitForm.damageUuid': id,
      'submitForm.company': type,
      diseaseName: name,
      diseasePopup: false,
      isStopBodyScroll: false,
    })
  },


  // -----start程度清零start-----
  damageDegreeClear() {
    this.setData({
      'submitForm.damageDegree': 0
    })
  },
  // 程度选择
  damageDegreeChange(e) {
    this.setData({
      'submitForm.damageDegree': e.detail
    })
  },
  // -----end程度说明end-----
  degreeTip() {
    this.setData({
      degreeShow: true
    })
  },

  // -----end问题数量end-----
  problemNum(e) {
    this.setData({
      'submitForm.problemNum': e.detail.value
    })
  },
  // -----end处理时限end-----
  limitTime(e) {
    this.setData({
      'submitForm.limitTime': e.detail.value
    })
  },
  // -----end问题描述end-----
  problemDescribe(e) {
    this.setData({
      'submitForm.problemDescribe': e.detail.value
    })
  },


  // -----end提交病害上报end-----
  submit() {
    // 腾讯地图逆地址解析
    // let qqmapsdk = new QQMapWX({
    //   key: 'XH6BZ-UBFRS-KCYOQ-6X3QI-H3QKK-E4BD7'
    // })
    // qqmapsdk.reverseGeocoder({
    //   location: {
    //     latitude: this.data.submitForm.latitude,
    //     longitude: this.data.submitForm.longitude
    //   },
    //   success: (res) => {
    //     if (res.status == 0) {
    //       this.setData({
    //         'submitForm.place': `${res.result.address}-${res.result.formatted_addresses.recommend}`
    //       })
    //     }
    //   }
    // })
    // 图片路径处理
    if (this.data.fileList.length > 0) {
      this.data.fileList.map((item, index) => {
        this.setData({
          [`submitForm.img${index + 1}`]: item.url
        })
      })
    }
    if (this.data.submitForm.img1 == "") {
      wx.showToast({
        title: '请至少上传一张图片',
        icon: 'error',
        duration: 2000
      })
      return
    } else if (this.data.submitForm.facilitiesName == "") {
      wx.showToast({
        title: '请选择设施',
        icon: 'error',
        duration: 2000
      })
      return
    } else if (this.data.submitForm.partUuid == "") {
      wx.showToast({
        title: '请选择部件',
        icon: 'error',
        duration: 2000
      })
      return
    } else if (this.data.submitForm.componentUuid == "") {
      wx.showToast({
        title: '请选择构件',
        icon: 'error',
        duration: 2000
      })
      return
    } else if (this.data.submitForm.damageUuid == "") {
      wx.showToast({
        title: '请选择损害',
        icon: 'error',
        duration: 2000
      })
      return
    } else if (this.data.submitForm.problemNum == "") {
      wx.showToast({
        title: '请输入问题数量',
        icon: 'error',
        duration: 2000
      })
      return
    } else if (this.data.submitForm.limitTime == "") {
      wx.showToast({
        title: '请输入处理时限',
        icon: 'error',
        duration: 2000
      })
      return
    } else if (this.data.submitForm.problemDescribe == "") {
      wx.showToast({
        title: '请输入问题描述',
        icon: 'error',
        duration: 2000
      })
      return
    } else {
      wx.getStorage({
        key: 'userInfo',
        success: res => {
          if (res.errMsg = "getStorage:ok") {
            this.setData({
              'submitForm.reportPername': res.data.userName,
              'submitForm.reportUserId': res.data.uuid,
              'submitForm.sourceUnit': res.data.unitName,
              'submitForm.sourceUnitType': res.data.companyName,
            })
            // 发送请求
            app.wxRequest("POST", "reportCuring/insertOrUpdateReport", this.data.submitForm, (res) => {
              if (res.errcode == 0) {
                wx.navigateTo({ url: '/pages/home/home', })
              }
            }, (err) => {
              console.log(err)
            })
          }
        }
      })

    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.Location();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})